/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AjudaCusto.java
 *
 * Created on Jan 14, 2011, 10:38:02 AM
 */
package br.com.tbp.gui.financeiro;

import br.com.tbp.controle.ControleAjudaCusto;
import br.com.tbp.controle.ControleConsultor;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.AjudaCustoFrame;
import br.com.tbp.model.domain.Consultor;
import br.com.tbp.model.domain.constant.TipoConsultor;
import br.com.tbp.model.domain.financeiro.AjudaCusto;
import br.com.tbp.model.domain.financeiro.StatusAjuda;
import br.com.tbp.utils.ColorUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import um.filteredtext.number.CurrencyNumberAdapter;
import um.filteredtext.number.IntegerNumberAdapter;

/**
 *
 * @author Diego Freire
 */
public class AjudaCustoDialog extends javax.swing.JDialog {

    private boolean novaAjuda;
    private AjudaCusto ajuda;
    private CurrencyNumberAdapter valorFormatter;
    private IntegerNumberAdapter acessosFormatter, fechamentoNumberAdapter;
    private AjudaCustoFrame parentWindow;

    public AjudaCustoDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        if (parent instanceof AjudaCustoFrame) {
            this.parentWindow = (AjudaCustoFrame) parent;
        }
        setLocationRelativeTo(null);
        carregaConsultores();
        configNumeralsTextField();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        cabecalhoPanel = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        descricaoField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        obsTextArea = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        dataTextField = new org.jdesktop.swingx.JXDatePicker();
        jLabel6 = new javax.swing.JLabel();
        valorField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        consultorCombo = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        acessoField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        statusCombo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        fechamentoField = new javax.swing.JTextField();
        restanteLabel = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        tipoCombo = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        novoButton = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        contentPanel.setLayout(new java.awt.BorderLayout());

        jPanel1.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel1.setLayout(new java.awt.BorderLayout());

        cabecalhoPanel.setBackground(new java.awt.Color(255, 255, 255));
        cabecalhoPanel.setPreferredSize(new java.awt.Dimension(103, 74));
        cabecalhoPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setForeground(new java.awt.Color(0, 0, 0));
        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/ajuda32x32.png"))); // NOI18N
        msgLabel.setText("msg");
        cabecalhoPanel.add(msgLabel);

        jPanel1.add(cabecalhoPanel, java.awt.BorderLayout.CENTER);

        contentPanel.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Básicas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel1.setText("Código:");

        idTextField.setEditable(false);
        idTextField.setFocusable(false);

        jLabel2.setText("Descrição:");

        jLabel3.setText("Observações:");

        obsTextArea.setColumns(20);
        obsTextArea.setLineWrap(true);
        obsTextArea.setRows(5);
        obsTextArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(obsTextArea);

        jLabel5.setText("Data:");

        jLabel6.setText("Valor:");

        jLabel7.setText("Consultor:");

        jLabel4.setText("Acessos:");

        jLabel8.setText("Status:");

        statusCombo.setModel(new DefaultComboBoxModel(br.com.tbp.model.domain.financeiro.StatusAjuda.values()));

        jLabel9.setText("Fechamento:");

        fechamentoField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                fechamentoFieldFocusGained(evt);
            }
        });

        restanteLabel.setForeground(new java.awt.Color(255, 51, 51));
        restanteLabel.setText("25");
        restanteLabel.setToolTipText("Acessos Restantes");

        jLabel10.setText("Tipo:");

        tipoCombo.setModel(new DefaultComboBoxModel(TipoConsultor.values()));
        tipoCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tipoComboItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                            .addGap(30, 30, 30)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(descricaoField, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel6)
                                .addComponent(jLabel5)
                                .addComponent(jLabel7)
                                .addComponent(jLabel4)
                                .addComponent(jLabel8)
                                .addComponent(jLabel9)
                                .addComponent(jLabel10))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(dataTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(valorField, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(consultorCombo, javax.swing.GroupLayout.Alignment.TRAILING, 0, 476, Short.MAX_VALUE)
                                .addComponent(acessoField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(tipoCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                                        .addComponent(fechamentoField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(restanteLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addComponent(statusCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, 182, Short.MAX_VALUE)))))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(descricaoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dataTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(consultorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(tipoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(acessoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechamentoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(restanteLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        contentPanel.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.BorderLayout());

        novoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/plus_16.png"))); // NOI18N
        novoButton.setMnemonic('n');
        novoButton.setText("Nova Ajuda");
        novoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoButtonActionPerformed(evt);
            }
        });
        jPanel5.add(novoButton);

        jPanel4.add(jPanel5, java.awt.BorderLayout.LINE_START);

        salvarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/accept.png"))); // NOI18N
        salvarButton.setMnemonic('s');
        salvarButton.setText("Salvar");
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        jPanel6.add(salvarButton);

        fecharButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        fecharButton.setText("Fechar");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel6.add(fecharButton);

        jPanel4.add(jPanel6, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel4, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void novoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoButtonActionPerformed
        setAjudaCusto(new AjudaCusto());
        setNovaAjudaCusto(true);
}//GEN-LAST:event_novoButtonActionPerformed

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();
            ControleAjudaCusto controle = new ControleAjudaCusto();
            AjudaCusto ajudaCusto = this.getAjudaCusto();
            if (isNovaAjudaCusto()) {
                if (controle.isLiberarAjuda(ajudaCusto.getConsultor())) {
                    controle.adicionar(ajudaCusto);
                    msgLabel.setText("A ajuda de custo foi adicionada com sucesso");
                } else {
                    JOptionPane.showMessageDialog(this, "Não é possível liberar outra ajuda de custo para o consultor '" + ajuda.getConsultor().toString2()
                            + "',\nsendo necessário quitar a anterior.", "Mensagem do sistema", 2);
                }
            } else {
                controle.atualizar(ajudaCusto);
                restanteLabel.setText(ajudaCusto.getAcessosRestantes());
                msgLabel.setText("Os dados da ajuda de custo foram atualizados com sucesso");
                if (getParentWindow() != null) {
                    getParentWindow().getTableModel().fireTableDataChanged();
                }
            }
        } catch (InputValidationException ivex) {
            msgLabel.setText(ivex.getMessage());
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
}//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        this.dispose();
}//GEN-LAST:event_fecharButtonActionPerformed

    private void fechamentoFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fechamentoFieldFocusGained
        fechamentoField.selectAll();
    }//GEN-LAST:event_fechamentoFieldFocusGained

    private void tipoComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tipoComboItemStateChanged
        if(evt.getStateChange() == ItemEvent.SELECTED) {
            try {
                TipoConsultor tipo = (TipoConsultor) tipoCombo.getSelectedItem();
                valorField.setText(valorFormatter.getNumberFormat().formatNumber(tipo.getValor()));
                acessoField.setText(acessosFormatter.getNumberFormat().formatNumber(tipo.getAcessos()));
            } catch(Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }//GEN-LAST:event_tipoComboItemStateChanged

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AjudaCustoDialog dialog = new AjudaCustoDialog(new javax.swing.JFrame(), "TBP - Ajuda de Custo", true);
                dialog.setAjudaCusto(new AjudaCusto());
                dialog.setNovaAjudaCusto(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField acessoField;
    private javax.swing.JPanel cabecalhoPanel;
    private javax.swing.JComboBox consultorCombo;
    private javax.swing.JPanel contentPanel;
    private org.jdesktop.swingx.JXDatePicker dataTextField;
    private javax.swing.JTextField descricaoField;
    private javax.swing.JTextField fechamentoField;
    private javax.swing.JButton fecharButton;
    private javax.swing.JTextField idTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton novoButton;
    private javax.swing.JTextArea obsTextArea;
    private javax.swing.JLabel restanteLabel;
    private javax.swing.JButton salvarButton;
    private javax.swing.JComboBox statusCombo;
    private javax.swing.JComboBox tipoCombo;
    private javax.swing.JTextField valorField;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    public boolean isNovaAjudaCusto() {
        return novaAjuda;
    }

    public void setNovaAjudaCusto(boolean n) {
        this.novaAjuda = n;
        if (isNovaAjudaCusto()) {
            msgLabel.setText("Forneça os dados para a nova ajuda de custo");
            isSomenteLeitura(false);
            statusCombo.setEnabled(false);
            fechamentoField.setEditable(false);
            restanteLabel.setVisible(false);
            tipoCombo.setSelectedItem(null);
        } else {
            isSomenteLeitura(true);
            msgLabel.setText("Visualização dos dados da ajuda de custo nº " + this.ajuda.getId() + "   [Somente-Leitura]");
        }
        descricaoField.requestFocus();
    }

    public AjudaCusto getAjudaCusto() {
        ajuda.setDescricao(descricaoField.getText());
        ajuda.setDataLiberacao(dataTextField.getDate());
        ajuda.setConsultor((Consultor) consultorCombo.getSelectedItem());
        ajuda.setTipo((TipoConsultor) tipoCombo.getSelectedItem());
        try {
            Number valor = valorFormatter.getNumberFormat().parseNumber(valorField.getText());
            ajuda.setValor(new Double(valor.toString()));
        } catch (ParseException pex) {
            System.out.println(pex.getMessage());
        }
        ajuda.setAcessos(Integer.parseInt(acessoField.getText()));
        ajuda.setFechamento(Integer.parseInt(fechamentoField.getText()));
        ajuda.setStatus((StatusAjuda) statusCombo.getSelectedItem());
        ajuda.setObservacao(obsTextArea.getText());
        return ajuda;
    }

    public void setAjudaCusto(AjudaCusto ajuda) {
        this.ajuda = ajuda;

        idTextField.setText("" + ajuda.getId());
        descricaoField.setText(ajuda.getDescricao());
        dataTextField.setDate(ajuda.getDataLiberacao());
        consultorCombo.setSelectedItem(ajuda.getConsultor());
        tipoCombo.setSelectedItem(ajuda.getTipo());
        if (ajuda.getValor() != null) {
            valorField.setText(valorFormatter.getNumberFormat().formatNumber(ajuda.getValor()));
        } else {
            valorField.setText(null);
        }
        acessoField.setText(ajuda.getAcessos() > 0 ? String.valueOf(ajuda.getAcessos()): null);
        fechamentoField.setText(String.valueOf(ajuda.getFechamento()));
        restanteLabel.setText(ajuda.getAcessosRestantes());
        statusCombo.setSelectedItem(ajuda.getStatus());
        obsTextArea.setText(ajuda.getObservacao());
        obsTextArea.setCaretPosition(0);
    }

    public void validarEntradaDoUsuario() throws InputValidationException {
        if (dataTextField.getDate() == null) {
            dataTextField.requestFocus();
            throw new InputValidationException("A data deve ser informada");
        }
        if (consultorCombo.getSelectedItem() == null) {
            consultorCombo.requestFocus();
            throw new InputValidationException("O consultor deve ser informado");
        }
        if (tipoCombo.getSelectedItem() == null) {
            tipoCombo.requestFocus();
            throw new InputValidationException("O tipo do consultor deve ser informado");
        }
        if (valorField.getText().isEmpty()) {
            valorField.requestFocus();
            throw new InputValidationException("O valor R$ deve ser informado");
        }
        if (acessoField.getText().isEmpty()) {
            acessoField.requestFocus();
            throw new InputValidationException("O número de acessos deve ser informado");
        }

    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    private void configNumeralsTextField() {
        valorFormatter = new CurrencyNumberAdapter(false);
        valorField.addKeyListener(valorFormatter);
        valorField.addFocusListener(valorFormatter);

        acessosFormatter = new IntegerNumberAdapter(false);
        acessoField.addKeyListener(acessosFormatter);
        acessoField.addFocusListener(acessosFormatter);

        fechamentoNumberAdapter = new IntegerNumberAdapter(false);
        fechamentoField.addKeyListener(fechamentoNumberAdapter);
        fechamentoField.addFocusListener(fechamentoNumberAdapter);
    }

    private void carregaConsultores() {
        ControleConsultor controle = new ControleConsultor();
        try {
            List<Consultor> lista = controle.pesquisar();
            consultorCombo.setModel(new DefaultComboBoxModel(lista.toArray()));
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public AjudaCustoFrame getParentWindow() {
        return parentWindow;
    }

    private void isSomenteLeitura(boolean b) {
        descricaoField.setEditable(!b);
        descricaoField.setFocusable(!b);
        dataTextField.setEditable(!b);
        dataTextField.setFocusable(!b);
        consultorCombo.setEnabled(!b);
        tipoCombo.setEnabled(!b);
        valorField.setEditable(!b);
        valorField.setFocusable(!b);
        acessoField.setEditable(!b);
        acessoField.setFocusable(!b);
        fechamentoField.setEditable(!b);
        fechamentoField.setFocusable(!b);
        statusCombo.setEnabled(!b);
        obsTextArea.setEditable(!b);
        obsTextArea.setFocusable(!b);
        salvarButton.setEnabled(!b);
        fecharButton.requestFocus();
        colorirCabecalho();
    }

    private void colorirCabecalho() {
        if (ajuda.getStatus().equals(StatusAjuda.PENDENTE)) {
            cabecalhoPanel.setBackground(ColorUtils.getVermelhoClaro());
        } else if (ajuda.getStatus().equals(StatusAjuda.QUITADA)) {
            cabecalhoPanel.setBackground(ColorUtils.getVerdeClaro());
        }
    }
}
